package com.seu.vcampus.handler;

import com.seu.vcampus.dao.BorrowRecordDao;
import com.seu.vcampus.message.Message;
import com.seu.vcampus.service.LibraryService;
import com.seu.vcampus.util.PermissionUtil;
import com.seu.vcampus.vo.Book;
import com.seu.vcampus.vo.BorrowRecord;
import com.seu.vcampus.vo.User;
import java.sql.Connection;
import java.util.List;

/**
 * 图书馆消息处理器
 * 处理图书馆相关的消息请求
 * 
 * @author 虚拟校园开发团队
 * @since 1.0.0
 */
public class LibraryHandler {
    private final LibraryService libraryService;
    private final BorrowRecordDao borrowRecordDao;
    
    public LibraryHandler(Connection connection) {
        this.libraryService = new LibraryService(connection);
        this.borrowRecordDao = new BorrowRecordDao(connection);
    }
    
    /**
     * 处理图书馆相关消息
     */
    public Message handle(Message request) {
        try {
            Message.Type type = request.getType();
            if (type == Message.Type.GET_BOOKS_REQUEST) {
                return handleGetBooksRequest(request);
            } else if (type == Message.Type.SEARCH_BOOKS_REQUEST) {
                return handleSearchBooksRequest(request);
            } else if (type == Message.Type.BORROW_BOOK_REQUEST) {
                return handleBorrowBookRequest(request);
            } else if (type == Message.Type.RETURN_BOOK_REQUEST) {
                return handleReturnBookRequest(request);
            } else if (type == Message.Type.GET_BORROW_RECORDS_REQUEST) {
                return handleGetBorrowRecordsRequest(request);
            } else if (type == Message.Type.GET_ALL_BORROW_RECORDS_REQUEST) {
                return handleGetAllBorrowRecordsRequest(request);
            } else if (type == Message.Type.ADD_BOOK_REQUEST) {
                return handleAddBookRequest(request);
            } else if (type == Message.Type.UPDATE_BOOK_REQUEST) {
                return handleUpdateBookRequest(request);
            } else if (type == Message.Type.DELETE_BOOK_REQUEST) {
                return handleDeleteBookRequest(request);
            } else if (type == Message.Type.GET_BOOK_BY_ID_REQUEST) {
                return handleGetBookByIdRequest(request);
            } else if (type == Message.Type.CHECK_BOOK_BORROWED_REQUEST) {
                return handleCheckBookBorrowedRequest(request);
            } else {
                return Message.error("未知的消息类型");
            }
        } catch (Exception e) {
            return Message.error("处理图书馆消息时发生错误: " + e.getMessage());
        }
    }
    
    /**
     * 处理获取所有图书请求
     */
    private Message handleGetBooksRequest(Message request) {
        List<Book> books = libraryService.getAllBooks();
        return Message.success(Message.Type.GET_BOOKS_RESPONSE, books);
    }
    
    /**
     * 处理搜索图书请求
     */
    private Message handleSearchBooksRequest(Message request) {
        String keyword = (String) request.getPayload();
        List<Book> books = libraryService.searchBooks(keyword);
        return Message.success(Message.Type.SEARCH_BOOKS_RESPONSE, books);
    }
    
    /**
     * 处理借阅图书请求
     */
    private Message handleBorrowBookRequest(Message request) {
        BorrowRecord record = (BorrowRecord) request.getPayload();
        String userId = record.getUserId();
        String bookId = record.getBookId();
        
        boolean success = libraryService.borrowBook(userId, bookId);
        if (success) {
            return Message.success(Message.Type.BORROW_BOOK_RESPONSE, true);
        } else {
            return Message.error("借阅失败，可能的原因：库存不足、已借阅过此书或达到借阅上限");
        }
    }
    
    /**
     * 处理归还图书请求
     */
    private Message handleReturnBookRequest(Message request) {
        String recordId = (String) request.getPayload();
        
        // 先通过recordId获取借阅记录，然后获取bookId
        BorrowRecord record = borrowRecordDao.getBorrowRecordById(Integer.parseInt(recordId));
        if (record == null) {
            return Message.error("借阅记录不存在");
        }
        
        boolean success = libraryService.returnBook(Integer.parseInt(recordId), record.getBookId());
        if (success) {
            return Message.success(Message.Type.RETURN_BOOK_RESPONSE, true);
        } else {
            return Message.error("归还失败");
        }
    }
    
    /**
     * 处理获取借阅记录请求
     */
    private Message handleGetBorrowRecordsRequest(Message request) {
        String userId = (String) request.getPayload();
        List<BorrowRecord> records = libraryService.getBorrowRecords(userId);
        return Message.success(Message.Type.GET_BORROW_RECORDS_RESPONSE, records);
    }
    
    /**
     * 处理获取所有借阅记录请求（管理员专用）
     */
    private Message handleGetAllBorrowRecordsRequest(Message request) {
        List<BorrowRecord> records = libraryService.getAllBorrowRecords();
        return Message.success(Message.Type.GET_ALL_BORROW_RECORDS_RESPONSE, records);
    }
    
    /**
     * 处理添加图书请求（管理员专用）
     */
    private Message handleAddBookRequest(Message request) {
        Book book = (Book) request.getPayload();
        
        // 检查图书ID是否已存在
        if (libraryService.getBookById(book.getBookId()) != null) {
            return Message.error("图书ID已存在");
        }
        
        boolean success = libraryService.addBook(book);
        if (success) {
            return Message.success(Message.Type.ADD_BOOK_RESPONSE, true);
        } else {
            return Message.error("添加图书失败");
        }
    }
    
    /**
     * 处理更新图书请求（管理员专用）
     */
    private Message handleUpdateBookRequest(Message request) {
        Book book = (Book) request.getPayload();
        
        // 检查图书是否存在
        if (libraryService.getBookById(book.getBookId()) == null) {
            return Message.error("图书不存在");
        }
        
        boolean success = libraryService.updateBook(book);
        if (success) {
            return Message.success(Message.Type.UPDATE_BOOK_RESPONSE, true);
        } else {
            return Message.error("更新图书失败");
        }
    }
    
    /**
     * 处理删除图书请求（管理员专用）
     */
    private Message handleDeleteBookRequest(Message request) {
        String bookId = (String) request.getPayload();
        
        // 检查图书是否存在
        if (libraryService.getBookById(bookId) == null) {
            return Message.error("图书不存在");
        }
        
        // 检查是否有未归还的借阅
        if (libraryService.isBookBorrowed(bookId)) {
            return Message.error("图书有未归还的借阅记录，无法删除");
        }
        
        boolean success = libraryService.deleteBook(bookId);
        if (success) {
            return Message.success(Message.Type.DELETE_BOOK_RESPONSE, true);
        } else {
            return Message.error("删除图书失败");
        }
    }
    
    /**
     * 处理根据ID获取图书请求
     */
    private Message handleGetBookByIdRequest(Message request) {
        String bookId = (String) request.getPayload();
        Book book = libraryService.getBookById(bookId);
        if (book != null) {
            return Message.success(Message.Type.GET_BOOK_BY_ID_RESPONSE, book);
        } else {
            return Message.error("图书不存在");
        }
    }
    
    /**
     * 处理检查图书是否被借阅请求
     */
    private Message handleCheckBookBorrowedRequest(Message request) {
        String bookId = (String) request.getPayload();
        boolean isBorrowed = libraryService.isBookBorrowed(bookId);
        return Message.success(Message.Type.CHECK_BOOK_BORROWED_RESPONSE, isBorrowed);
    }
}